package com.imu.purse.modules.trade.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.xiaoleilu.hutool.util.NumberUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.imu.common.exception.RRException;
import com.imu.core.base.BaseService;
import com.imu.core.redis.annotation.RedisLock;
import com.imu.datasources.DataSourceNames;
import com.imu.datasources.annotation.DataSource;
import com.imu.enums.PStatus;
import com.imu.purse.modules.trade.dao.YmbDetailMapper;
import com.imu.purse.modules.trade.entity.FundEntity;
import com.imu.purse.modules.trade.entity.TradeInfoEntity;
import com.imu.purse.modules.trade.entity.YmbDetailEntity;
import com.imu.purse.modules.trade.service.FundService;
import com.imu.purse.modules.trade.service.TradeInfoService;
import com.imu.purse.modules.trade.service.YmbDetailService;

/**
 * 易买宝充值详情表
 * @author sunhongwei
 * @email sunhongwei@jshijian.com
 * @date 2018-07-02 23:47:18
 * Copyright (c) 2017 武汉极时间科技有限公司 版权所有 
 * Jshijian aloha CO.,LTD. All Rights Reserved. 
 */
@Service
public class YmbDetailServiceImpl extends BaseService<YmbDetailEntity> implements YmbDetailService 
{
	@Override
    @Transactional
    public int save(final YmbDetailEntity ymbDetail)
	{
		ymbDetail.setCreateTime(System.currentTimeMillis());
		ymbDetail.setUpdateTime(System.currentTimeMillis());
    	return super.insert(ymbDetail);
	}
	
	@Override
	@Transactional
    public int update(final YmbDetailEntity ymbDetail) 
    {
    	ymbDetail.setUpdateTime(System.currentTimeMillis());
    	return mapper.updateByPrimaryKeySelective(ymbDetail);
    }
    
    @Override
	@Transactional
    public int saveUpdate(final YmbDetailEntity ymbDetail)
    {
    	int len = 0;
    	
    	if(1 > (len = this.update(ymbDetail)))
    	{
        	len = this.insert(ymbDetail);
    	}
    	
    	return len;
    }
    
 	@Override
	@Transactional
    public boolean delete(final String ...ids)
    {
    	if(ArrayUtil.isEmpty(ids)) return false;
    	
    	for (String id : ids) 
    	{
    		if(StrUtil.isBlank(id)) continue;
    		
    		if(NumberUtil.isNumber(id))
    		{
        		mapper.deleteByPrimaryKey(Long.valueOf(id));
    		}
		}
    	
    	return true;
    }

 	@Override
	@Transactional
	@RedisLock(keys = "#key", expire = 30000, tryTimeout = 1000)
 	public void charge(final String key, final YmbDetailEntity entity, final boolean flag, final Long userId)
 	{
 		if(null == userId || 0 >= userId || null == entity || null == entity.getUserId()) return;
 		FundEntity funEntity = fundService.findByUserId(entity.getUserId());
 		if(null == funEntity || null == funEntity.getBj()) throw new RRException("收款账户不存在，请核实", 6001);
 		FundEntity useEntity = fundService.findByUserId(userId);
 		if(null == useEntity || null == useEntity.getBj()) throw new RRException("付款账户不存在，请联系管理员", 6002);
 		
 		//保存充值记录
 		if(flag) {
 			entity.setSource(1);
 			entity.setOrderState(PStatus.Finished.getType());
 			save(entity); 
 		}
 		else { 
 			if(null == entity.getId()) return;
 			YmbDetailEntity dto = new YmbDetailEntity();
 			dto.setId(entity.getId());
 			dto.setOrderState(entity.getOrderState());
 			dto.setDescription(entity.getDescription());
 			dto.setUpdateUser(entity.getUpdateUser());
 			this.update(dto);
 		}
 		
 		if(entity.getOrderState().intValue() == PStatus.Finished.getType())
 		{
 			//修改用户BJ
 			FundEntity fund = new FundEntity();
 			fund.setUserId(entity.getUserId());
 			fund.setBj(entity.getMoney());
 			fundService.upBjMoney(fund);
 			
 			//保存流水记录
 			TradeInfoEntity tradeInfoEntity = new TradeInfoEntity();
 			tradeInfoEntity.setPayUserId(entity.getUserId());
	        tradeInfoEntity.setRecUserId(userId);
 			tradeInfoEntity.setOrderNo(entity.getId().toString());
 			tradeInfoEntity.setMoney(entity.getMoney().abs());
 			tradeInfoEntity.setSmoney(funEntity.getBj());
 			tradeInfoEntity.setEmoney(funEntity.getBj().add(entity.getMoney()));
 			tradeInfoEntity.setDetail(entity.getDescription());
 			tradeInfoEntity.setOrderType(-1 == entity.getMoney().compareTo(new BigDecimal(0)) ? 0 : 2);
 			tradeInfoEntity.setOrderState(1);
 			tradeInfoEntity.setYtfType(2);
 			tradeInfoEntity.setOrderCreate(new Date());
 			tradeInfoService.save(tradeInfoEntity);
 			//修改系统用户BJ
	        fund.setUserId(userId.longValue());
	        fund.setBj(entity.getMoney().multiply(new BigDecimal(-1)));
			fundService.upBjMoney(fund);
			
	        tradeInfoEntity.setId(null);
	        tradeInfoEntity.setPayUserId(userId);
	        tradeInfoEntity.setRecUserId(entity.getUserId());
	        tradeInfoEntity.setOrderNo(entity.getId().toString());
	        tradeInfoEntity.setMoney(entity.getMoney().abs());
 			tradeInfoEntity.setSmoney(useEntity.getBj());
 			tradeInfoEntity.setEmoney(useEntity.getBj().subtract(entity.getMoney()));
	        tradeInfoEntity.setOrderType(-1 == entity.getMoney().compareTo(new BigDecimal(0)) ? 2 : 0);
	        tradeInfoEntity.setYtfType(2);
 			tradeInfoEntity.setOrderCreate(new Date());
	        tradeInfoService.save(tradeInfoEntity);
 		}
 	}
    
    @Override
    @DataSource(name=DataSourceNames.SECOND)
    public YmbDetailEntity findById(final Long id)
    {
    	if(null == id) return null;
    	return mapper.selectByPrimaryKey(id);
    }
    
    @Override
    @DataSource(name=DataSourceNames.SECOND)
    public List<YmbDetailEntity> queryList(final YmbDetailEntity ymbDetail)
    {
    	if (ymbDetail.getPage() != null && ymbDetail.getLimit() != null)
    	{
            PageHelper.startPage(ymbDetail.getPage(), ymbDetail.getLimit());
        }
    	
    	return mapper.findByPage(ymbDetail);
    }
    
	@Autowired
	private YmbDetailMapper mapper;

	@Autowired
	private FundService fundService;
	
	@Autowired
	private TradeInfoService tradeInfoService;
}
